<?php

namespace app\home\controller;


use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\BaseController;
use think\App;
use think\facade\Env; 
use think\facade\Cache; 
use think\facade\Session; 
use app\common\controller\HomeBaseController;

use think\facade\Db;
use app\api\model\ServerUser;


class Index extends HomeBaseController
{


    public function bindwechat($server_user_id)
    {
    	if( empty($server_user_id )){
          
               $this -> assign("img_url",'https://'.$_SERVER['HTTP_HOST']."/assets/img/error.jpg");

        }else{

             Session::set('server_user_id',$server_user_id);
             $this->getcode();
        }
   $this -> assign("img_url",'https://'.$_SERVER['HTTP_HOST']."/assets/img/error.jpg");
    	$site_version = cache::get('site_version');
        $this->assign('version', $site_version);
        return $this->fetch();
    }





    //获取openid
    public function wxlogin(){
           $appid= Env::get('wx_chat.wx_appid_fwh','wxbf9de640ad23e5a7');
           $appsecret= Env::get('wx_chat.wx_secret_fwh','b1fb23e6d0b1283ddf5b19c3fc7b8747');
     
           $appsecret= 'b1fb23e6d0b1283ddf5b19c3fc7b8747';
           // $Token=Env::get('wx_chat.wx_token_fwh');
           // $Crypt = $wechat['EncodingAESKey'];
           $redirect_url= 'https://'.$_SERVER['HTTP_HOST'].'/home/index/wxlogin';
           $baseurl = urlencode($redirect_url);
           $snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YSSKNET#wechat_redirect';


        //2.静默授权,获取code 
          
        $code=$_GET['code'];
        if( !isset($code) ){
          header('Location:'.$snsapi_base_url);
        }
        
        //3.通过code换取网页授权access_token和openid
        // $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";

        //     $oauth2 = $this->http_curl($oauth2Url);
        //     
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        //3.拉去用户的openid
        $res=file_get_contents($url);
        $arr=json_decode($res,true); 

           $openid = $arr['openid'];
            //openid
            // $openid = $oauth2['openid'];

        // session('access_token', $access_token);
        // session('openid', $openid);
            $this->get_userinfo($openid);
        

        return $this->fetch('index');
    }

    public function get_userinfo($openid){
      // $access_token=$this->get_access_token();
         
       //    $userinfo_url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; 
       //   $userinfo = $this->http_curl($userinfo_url);
      //       if(empty($userinfo)){
      //           $this->wxlogin();
      //       } 

            $update_info=array(
                'gzh_openid'=>$openid
            );
            $server_user_id=session::get('server_user_id');
          
          
            $res=DB::name('servers_user')->where('id',$server_user_id)->update($update_info);
    
 
            $message_res=$this->dowxmsg($openid);

        
        return $this->fetch('index');
        
    }


    // public function do_msg($openid,$){

    // }

    public function dowxmsg($openid)
       {
       
   
        $access_token=$this->get_access_token();

         $openid=$openid;//openid
         $templateId ='fmZNEHWfXccfjqiJu8lEPjBn_cobYAZnraWENIZCAmc';//微信模板ID

                 $driver_info=DB::name('new_driver')->where('gzh_openid',$openid)->find();
                 $car_info=DB::name('new_car')->where('server_user_id',$driver_info['id'])->find();
                 $driver_info['license_number']=$car_info['license_number'];
             

                 $data=array(
                           'first'=>array('value'=>urlencode("您好，您已开通公众号消息提醒"),'color'=>"#ff0041"),
                           'keyword1'=>array('value'=>$driver_info['license_number'],'color'=>'#333333'),
                           'keyword2'=>array('value'=>$driver_info['real_name'],'color'=>'#333333'),
                           'keyword3'=>array('value'=>'您已开通微信消息提醒','color'=>'#333333'),
                           'remark'=>array('value'=>urlencode('如有疑问，请联系客服！'),'color'=>'#ff0041'),
                       );
         $wxurl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
         $url='';
         $params1=array(
            "touser"=>$openid,
            "template_id"=>$templateId,
              "url"=>$url,   
              "data"=>$data
         );
          $json_template = json_encode($params1);
          $params = $this->curl_post($wxurl,urldecode($json_template));
          $params = json_decode($params,true);
            
                 if ($params['errcode']==0){
                  
        
      $this -> assign("img_url",'https://'.$_SERVER['HTTP_HOST']."/assets/img/success.jpg");
                 }else{
                  
        
      $this -> assign("img_url",'https://'.$_SERVER['HTTP_HOST']."/assets/img/success_guanzhu.jpg");
                 }

                 
        return $this->fetch('index');
       
       }




    public function getcode(){ 
      $appid= Env::get('wx_chat.wx_appid_fwh');
      $redirect_url= 'https://'.$_SERVER['HTTP_HOST'].'/home/index/wxlogin';
      $baseurl = urlencode($redirect_url);
      $snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YSSKNET#wechat_redirect';
      header("location:".$snsapi_base_url);
 
    }

    //获取access_token
    public function get_access_token(){
             $appid= Env::get('wx_chat.wx_appid_fwh');
             $appsecret= Env::get('wx_chat.wx_secret_fwh');
             $Token=Env::get('wx_chat.wx_token_fwh');

            if(Session::get('access_token_expire_time')>time() && Session::get('access_token')){
                $access_token=session::get('access_token');
             }else{
                $snsapi_base_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
                $arr=$this->http_curl($snsapi_base_url);
      

                $access_token=$arr['access_token']; 
                Session::set("access_token",$access_token);
                Session::set("access_token_expire_time",time()+6000);

             }
             
            return  $access_token;
    }


    public  function http_curl($url){
        //用curl传参
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
     
        //关闭ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     
     
        curl_setopt($ch,CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

     public function curl_post($url , $data=array()){
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
              // POST数据
              curl_setopt($ch, CURLOPT_POST, 1);
              // 把post的变量加上
              curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
              $output = curl_exec($ch);
              curl_close($ch);
              return $output;
          }

 

}
